const axios = require('axios');
const config = require('../../config');

class FeishuApiService {
  constructor() {
    // 飞书API基础地址
    this.baseURL = 'https://open.feishu.cn/open-apis';
    // 从配置文件或环境变量获取App ID和App Secret
    this.appId = config.feishu.appId || process.env.FEISHU_APP_ID || '';
    this.appSecret = config.feishu.appSecret || process.env.FEISHU_APP_SECRET || '';
    this.accessToken = null;
    this.tokenExpireTime = null;
  }

  /**
   * 获取访问令牌
   */
  async getAccessToken() {
    try {
      // 如果token未过期，直接返回
      if (this.accessToken && this.tokenExpireTime && Date.now() < this.tokenExpireTime) {
        return this.accessToken;
      }

      const response = await axios.post(`${this.baseURL}/auth/v3/tenant_access_token/internal`, {
        app_id: this.appId,
        app_secret: this.appSecret
      }, {
        headers: {
          'Content-Type': 'application/json'
        }
      });

      if (response.data.code === 0) {
        this.accessToken = response.data.tenant_access_token;
        // token有效期通常是2小时，提前5分钟刷新
        this.tokenExpireTime = Date.now() + (response.data.expire - 300) * 1000;
        return this.accessToken;
      } else {
        throw new Error(`获取token失败: ${response.data.msg}`);
      }
    } catch (error) {
      console.error('获取访问令牌失败:', error);
      throw error;
    }
  }

  /**
   * 获取消息内容
   * @param {string} messageId 消息ID
   * @returns {Promise<object>} 消息内容
   */
  async getMessage(messageId) {
    try {
      const token = await this.getAccessToken();
      
      const response = await axios.get(
        `${this.baseURL}/im/v1/messages/${messageId}`,
        {
          headers: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
          }
        }
      );

      if (response.data.code === 0) {
        return response.data.data;
      } else {
        throw new Error(`获取消息失败: ${response.data.msg}`);
      }
    } catch (error) {
      console.error('获取消息内容失败:', error);
      throw error;
    }
  }

  /**
   * 发送消息
   * @param {string} receiveId 接收者ID（用户ID或群ID）
   * @param {string} receiveIdType 接收者类型：open_id, user_id, chat_id
   * @param {string} msgType 消息类型：text, post, image等
   * @param {object} content 消息内容
   * @returns {Promise<object>} 发送结果
   */
  async sendMessage(receiveId, receiveIdType, msgType, content) {
    try {
      const token = await this.getAccessToken();
      
      const response = await axios.post(
        `${this.baseURL}/im/v1/messages`,
        {
          receive_id: receiveId,
          receive_id_type: receiveIdType,
          msg_type: msgType,
          content: JSON.stringify(content)
        },
        {
          headers: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
          }
        }
      );

      if (response.data.code === 0) {
        return response.data.data;
      } else {
        throw new Error(`发送消息失败: ${response.data.msg}`);
      }
    } catch (error) {
      console.error('发送消息失败:', error);
      throw error;
    }
  }

  /**
   * 解析消息内容
   * @param {object} message 消息对象
   * @returns {string} 解析后的文本内容
   */
  parseMessageContent(message) {
    if (!message || !message.body) {
      return '';
    }

    const { content } = message.body;
    if (!content) {
      return '';
    }

    try {
      // 如果是JSON字符串，需要解析
      let parsedContent = typeof content === 'string' ? JSON.parse(content) : content;
      
      // 根据消息类型解析内容
      if (parsedContent.text) {
        return parsedContent.text;
      } else if (parsedContent.post) {
        // 富文本消息
        return this.parsePostContent(parsedContent.post);
      } else if (parsedContent.image) {
        return `[图片消息]`;
      } else if (parsedContent.file) {
        return `[文件消息]`;
      } else {
        return JSON.stringify(parsedContent);
      }
    } catch (error) {
      console.error('解析消息内容失败:', error);
      return content;
    }
  }

  /**
   * 解析富文本消息
   * @param {object} post 富文本内容
   * @returns {string} 文本内容
   */
  parsePostContent(post) {
    if (!post || !post.zh_cn) {
      return '';
    }

    const { title, content } = post.zh_cn;
    let text = title ? `标题: ${title}\n` : '';
    
    if (content && Array.isArray(content)) {
      content.forEach(paragraph => {
        if (paragraph.tag === 'text') {
          text += paragraph.text || '';
        } else if (paragraph.tag === 'a') {
          text += paragraph.text || paragraph.href || '';
        } else if (paragraph.tag === 'at') {
          text += `@${paragraph.user_name || paragraph.user_id || ''}`;
        }
      });
    }
    
    return text;
  }
}

module.exports = new FeishuApiService();

